import json

def parse_json_document(json_arr):
    parsed_documents = []
        
    for arr in json_arr:
        new_arr = str(arr).replace("\\", "")
        new_arr = new_arr.replace("(", "")
        new_arr = new_arr.replace(")", "")
        new_arr = new_arr.replace("'", "")
        data = json.loads(new_arr[:-1])
        doc_id = data["doc_id"]
        document_name = data["document_name"]
        doc_desc = data["doc_desc"]
        questions = data["questions"]
        
        parsed_questions = []
        for question in questions:
            question_text = question["questionText"]
            question_type = question["qustionType"]
            options = question["options"]
            open = question["open"]
            required = question["required"]
            
            parsed_question = {
                "question_text": question_text,
                "question_type": question_type,
                "options": options,
                "open": open,
                "required": required,
            }
            parsed_questions.append(parsed_question)
            
        
        parsed_document = {
            "doc_id": doc_id,
            "document_name": document_name,
            "doc_desc": doc_desc,
            "questions": parsed_questions,
        }
        
        parsed_documents.append(parsed_document)
    return parsed_documents

def parse_to_json(Answer_id, doc_id, document_name, ans_data):
    parsed_data = {
        "Answer_id": Answer_id,
        "doc_id": doc_id,
        "document_name": document_name,
        "Answers": []
    }

    for index, item in enumerate(ans_data, 1):
        if item['answer']:
            num_ans = [i for i in range(1, len(item['answer']) + 1)]
        else:
            num_ans = []

        new_answer = {
            "Number_Question": index,
            "Question": item['question'],
            "Number_Ans": num_ans,
            "Answer": item['answer']
        }
        parsed_data["Answers"].append(new_answer)

    json_str = json.dumps(parsed_data, ensure_ascii=False)
    return json_str
